<?php


namespace app\service\model;


use app\service\exception\BaseException;
use app\service\Y;

class CartModel extends BaseModel
{

    protected $table = 'cart';

    /**
     * 关联商品
     * @return \think\model\relation\BelongsTo
     */
    public function goods(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(GoodsModel::class, 'goods_id', 'id');
    }

    /**
     * 关联sku
     * @return \think\model\relation\BelongsTo
     */
    public function sku()
    {
        return $this->belongsTo(GoodsSkuModel::class, 'sku_id', 'id');
    }

    /**
     * 添加购物车
     * @param $param
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function addCart($param): \think\response\Json
    {
        $cart = self::where('member_id', '=', $param['member_id'])
            ->where('goods_id', '=', $param['goods_id'])
            ->where('sku_id', '=', $param['sku_id'])
            ->find();

        if ($cart) {
            $cart->inc('num')->update();
        } else {
            $sku = GoodsSkuModel::where('id', '=', $param['sku_id'])->where('goods_id', '=', $param['goods_id'])->find();
            if (!$sku) {
                throw new BaseException(['msg' => '商品不存在']);
            }
            $param['attribute'] = implode(' ', AttributeModel::where('id', 'in', $sku->attrs)->column('name'));
            self::create($param);
        }
        return Y::success([], '添加成功');
    }
}